package com.equipmentRent.web.controller;



import com.equipmentRent.common.annotation.Log;
import com.equipmentRent.common.config.RuoYiConfig;
import com.equipmentRent.common.core.domain.AjaxResult;
import com.equipmentRent.common.core.domain.entity.SysUser;
import com.equipmentRent.common.enums.BusinessType;
import com.equipmentRent.common.utils.DateUtils;
import com.equipmentRent.common.utils.ShiroUtils;
import com.equipmentRent.common.utils.StringUtils;
import com.equipmentRent.common.utils.file.FileUploadUtils;
import com.equipmentRent.common.utils.file.MimeTypeUtils;
import com.equipmentRent.framework.shiro.service.SysPasswordService;
import com.equipmentRent.system.domain.dto.ResetPwdDto;
import com.equipmentRent.system.service.ISysUserService;
import com.equipmentRent.web.controller.system.SysProfileController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.Objects;

import static com.equipmentRent.common.core.domain.AjaxResult.error;
import static com.equipmentRent.common.core.domain.AjaxResult.success;
import static com.equipmentRent.common.utils.ShiroUtils.getSysUser;
import static com.equipmentRent.common.utils.ShiroUtils.setSysUser;


@Controller
@RequestMapping("/user/center")
public class UserCenterController {

    private static final Logger log = LoggerFactory.getLogger(SysProfileController.class);

    @Resource
    private SysPasswordService passwordService;


    @Resource
    private ISysUserService userService;

    /**
     * 获取用户信息
     * @return
     */
    @PostMapping("/getUserInfo")
    @ResponseBody
    public AjaxResult getUserInfo(){
        SysUser sysUser = getSysUser();
        return success(sysUser);
    }


    /**
     * 修改密码
     * @return
     */
    @PostMapping("/resetPwd")
    @ResponseBody
    public AjaxResult resetPwd(@RequestBody ResetPwdDto dto) throws Exception {
        if (Objects.isNull(dto)){
            throw new Exception("请求参数错误");
        }
        String oldPassword = dto.getOldPassword();
        String newPassword = dto.getNewPassword();
        SysUser user = getSysUser();
        if (!passwordService.matches(user, oldPassword))
        {
            return error("修改密码失败，旧密码错误");
        }
        if (passwordService.matches(user, newPassword))
        {
            return error("新密码不能与旧密码相同");
        }
        user.setSalt(ShiroUtils.randomSalt());
        user.setPassword(passwordService.encryptPassword(user.getLoginName(), newPassword, user.getSalt()));
        user.setPwdUpdateDate(DateUtils.getNowDate());
        if (userService.resetUserPwd(user) > 0)
        {
            setSysUser(userService.selectUserById(user.getUserId()));
            return success();
        }
        return error("修改密码异常，请联系管理员");
    }

    /**
     * 校验新旧密码
     * @param password
     * @return
     */
    @GetMapping("/checkPassword")
    @ResponseBody
    public boolean checkPassword(String password)
    {
        SysUser user = getSysUser();
        return passwordService.matches(user, password);
    }

    /**
     * 修改用户个人详细信息
     * @param user
     * @return
     */
    @Log(title = "个人信息", businessType = BusinessType.UPDATE)
    @PostMapping("/update")
    @ResponseBody
    public AjaxResult update(@RequestBody SysUser user)
    {
        SysUser currentUser = getSysUser();
        currentUser.setUserName(user.getUserName());
        currentUser.setEmail(user.getEmail());
        currentUser.setPhonenumber(user.getPhonenumber());
        currentUser.setSex(user.getSex());
        if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(currentUser))
        {
            return error("修改用户'" + currentUser.getLoginName() + "'失败，手机号码已存在");
        }
        else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(currentUser))
        {
            return error("修改用户'" + currentUser.getLoginName() + "'失败，邮箱账号已存在");
        }
        if (userService.updateUserInfo(currentUser) > 0)
        {
            setSysUser(userService.selectUserById(currentUser.getUserId()));
            return success();
        }
        return error();
    }

    /**
     * 保存头像
     */
    @Log(title = "个人信息", businessType = BusinessType.UPDATE)
    @PostMapping("/updateAvatar")
    @ResponseBody
    public AjaxResult updateAvatar(@RequestParam("avatarfile") MultipartFile file)
    {
        SysUser currentUser = getSysUser();
        try
        {
            if (!file.isEmpty())
            {
                String avatar = FileUploadUtils.upload(RuoYiConfig.getAvatarPath(), file, MimeTypeUtils.IMAGE_EXTENSION);
                currentUser.setAvatar(avatar);
                if (userService.updateUserInfo(currentUser) > 0)
                {
                    setSysUser(userService.selectUserById(currentUser.getUserId()));
                    return success();
                }
            }
            return error();
        }
        catch (Exception e)
        {
            log.error("修改头像失败！", e);
            return error(e.getMessage());
        }
    }
}
